import os
import sys

from PySide6.QtCore import QUrl, QTimer
from PySide6.QtWebEngineCore import QWebEngineProfile
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWidgets import QApplication

project_path = os.path.dirname(os.path.abspath(__file__))
output_path=os.path.join(project_path,"output")
cookies_file_path=os.path.join(project_path,"data","cookies.txt")
cities_file_path=os.path.join(project_path,"data","cities.json")
def is_int_between(text, param):
    # 两边都是闭区间
    try:
        return param[0] <= int(text) <= param[1]
    except ValueError:
        return False

def is_int(text):
    try:
        int(text)
        return True
    except ValueError:
        return False
def while_input(tip, fun, param=None):
    while True:
        try:
            res = input(tip)
            if fun is None:
                return res
            if param is None:
                if fun(res):
                    return res
                else:
                    print('输入有误，请重新输入' )
            else:
                if fun(res, param):
                    return res
                else:
                    print('输入有误，请重新输入', )
        except Exception as e:
            print(f"{e}" )
            print('输入有误，请重新输入')



def create_folder():
    """创建文件夹"""
    data_path=os.path.join(project_path,"data")
    if not os.path.exists(data_path):
        os.mkdir(data_path)
    if not os.path.exists(output_path):
        os.mkdir(output_path)

def get_weather_cookies():
    if os.path.isfile(cookies_file_path):
        with open(cookies_file_path, "r") as f:
            return f.read()
    app = QApplication(sys.argv)
    cookies = ""
    def handle_cookie_added(cookie):
        print(cookie)
        nonlocal cookies
        cookie_name = cookie.name().data().decode('utf-8')
        if cookie_name in [
            'Hm_lpvt_080dabacb001ad3dc8b9b9049b36d43b',
            'Hm_lvt_080dabacb001ad3dc8b9b9049b36d43b',
            'HMACCOUNT',
            'f_city'
        ]:
            cookies += f"{cookie_name}={cookie.value().data().decode('utf-8')};"
    browser = QWebEngineView()
    profile = QWebEngineProfile.defaultProfile()
    profile.cookieStore().cookieAdded.connect(handle_cookie_added)
    browser.load(QUrl('https://www.weather.com.cn/'))
    browser.loadFinished.connect(lambda: QTimer.singleShot(0, app.quit))
    app.exec_()
    with open(cookies_file_path, "w") as f:
        f.write(cookies)
    return cookies